package com.nash.demands;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class DocHeadActivity extends Activity {
  
  public final static String TBL_TEMP_ITEM = "temp_item";
  public final static String TBL_TEMP_ITEM_ID_TU = "id_tu";
  public final static String TBL_TEMP_ITEM_AMOUNT = "amount";
  public final static String TBL_TEMP_ITEM_PRICE = "price";
  private static final String CREATE_TEMP_TABLE = "create temporary table if not exists " + TBL_TEMP_ITEM + " (" + BaseColumns._ID + " integer primary key autoincrement not null," + TBL_TEMP_ITEM_ID_TU
      + " integer unique, " + TBL_TEMP_ITEM_AMOUNT + " integer not null," + TBL_TEMP_ITEM_PRICE + " numeric not null)";
  private boolean insertMode;
  private long demandId;
  
  private TextView mDate;
  static final int DATE_DIALOG_ID = 0;
  public Spinner spnOsnr;
  public Spinner spnHost;
  public EditText etInfo;
  public boolean isEdited = false;
  public boolean sended;

  private long agentId;
  private long osnrId;
  private long hostId;
  private String agentName;
  private Date date;
  private Date demandDate;
  private String info;
  private Button btnPos;

  // ArrayList<String> spinnerArray = new ArrayList<String>();
  public void onCreate(Bundle savedInstanceState) {
    try {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.doc_head);

      //((DocTabActivity) this.getParent()).docHeadActivity = this;
      
      
      
      DemandsActivity.db.execSQL(CREATE_TEMP_TABLE);
      DemandsActivity.db.execSQL("delete from " + TBL_TEMP_ITEM);

      Bundle b = getIntent().getExtras();
      boolean sended = b.getInt("addit", 0)==0?false:true;
      demandId = b.getLong("demand_id", 0);

      insertMode = demandId == 0;
      if (!insertMode) {
        DemandsActivity.db.execSQL("insert into " + TBL_TEMP_ITEM + " (" + TBL_TEMP_ITEM_ID_TU + "," + TBL_TEMP_ITEM_AMOUNT + "," + TBL_TEMP_ITEM_PRICE + ") select " + Helper.TBL_DEMAND_LINE_ID_TU + ","
            + Helper.TBL_DEMAND_LINE_AMOUNT + "," + Helper.TBL_DEMAND_LINE_PRICE + " from " + Helper.TBL_DEMAND_LINE + " where " + Helper.TBL_DEMAND_LINE_ID_DEMAND + "=" + demandId);
      }
      
      osnrId = 0;
      hostId = 0;
      info = "";
      sended = false;
      String sDate = "";
      String sDemandDate = "";
      if (demandId == 0) {
        agentId = b.getLong("agent_id", 0);
        agentName = b.getString("agent_name");
        sDate = b.getString("date");
        sDemandDate = b.getString("date");
        isEdited = true;
      } else {
        date = new Date();
        demandDate = new Date();
        agentName = "";
        agentId = 0;
        StringBuilder sb = new StringBuilder().append(
            "select " + "a." + BaseColumns._ID + " as agentId,a." + Helper.TBL_AGENT_NAME + " as agentName,d." + Helper.TBL_DEMAND_DATE + " as date, d." + Helper.TBL_DEMAND_DEMAND_DATE + " as demandDate, d."
                + Helper.TBL_DEMAND_ID_HOST + " as id_host,d." + Helper.TBL_DEMAND_ID_OSNR + " as id_osnr,d." + Helper.TBL_DEMAND_INFO + " as info,d." + Helper.TBL_DEMAND_ADDIT + " as addit from " + Helper.TBL_DEMAND
                + " d," + Helper.TBL_AGENT + " a where d." + Helper.TBL_DEMAND_ID_AGENT + "=a." + BaseColumns._ID + " and d." + BaseColumns._ID + "=").append(demandId);
        Cursor data = DemandsActivity.db.rawQuery(sb.toString(), null);

        if (data.moveToFirst()) {
          agentId = data.getInt(data.getColumnIndex("agentId"));
          agentName = data.getString(data.getColumnIndex("agentName"));
          sDate = data.getString(data.getColumnIndex("date"));
          sDemandDate = data.getString(data.getColumnIndex("demandDate"));
          hostId = data.getInt(data.getColumnIndex("id_host"));
          osnrId = data.getInt(data.getColumnIndex("id_osnr"));
          info = data.getString(data.getColumnIndex("info"));
          sended = data.getInt(data.getColumnIndex("addit")) == 1 ? true : false;
        }

        if ((data != null) && !(data.isClosed()))
          data.close();
      }

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      sdf.parse(sDate);
      Calendar c = sdf.getCalendar();
      date = c.getTime();

      sdf.parse(sDemandDate);
      c = sdf.getCalendar();
      demandDate = c.getTime();

      TextView tvNo = (TextView) findViewById(R.id.textViewOrderNo);
      if (demandId > 0)
        tvNo.setText("" + demandId);

      TextView tvDemandDate = (TextView) findViewById(R.id.textViewDate);
      mDate = (TextView) findViewById(R.id.textDateO);
      updateDisplayDate();

      sdf = new SimpleDateFormat("dd-MM-yyyy");
      tvDemandDate.setText(sdf.format(demandDate));

      TextView tvAgent = (TextView) findViewById(R.id.textViewAgent);
      tvAgent.setText(agentName);

      spnHost = (Spinner) findViewById(R.id.spnHost);
      setAdapterHost(this);
      for (int i = 0; i < spnHost.getCount(); i++) {
        Cursor value = (Cursor) spnHost.getItemAtPosition(i);
        long id = value.getLong(value.getColumnIndex("_id"));
        if (id == hostId) {
          spnHost.setSelection(i);
        }
      }
      // just after filling and setSelection set trigger
      spnHost.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
          isEdited=true;
        }
        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
        }
      });

      spnOsnr = (Spinner) findViewById(R.id.spnOsnr);
      setAdapterOsnr(this);
      for (int i = 0; i < spnOsnr.getCount(); i++) {
        Cursor value = (Cursor) spnOsnr.getItemAtPosition(i);
        long id = value.getLong(value.getColumnIndex("_id"));
        if (id == osnrId) {
          spnOsnr.setSelection(i);
        }
      }

      etInfo = (EditText) findViewById(R.id.editTextComment);
      etInfo.setText(info);

      Button btnSave = (Button) findViewById(R.id.btnSave);
      btnSave.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
          saveDemand();
          Intent intent = new Intent();
          setResult(RESULT_OK, intent);
          finish();
        }

      });

      // btnCancel.setText(name+" "+String.valueOf(value));

      Button btnDel = (Button) findViewById(R.id.btnDelete);
      btnDel.setEnabled(demandId != 0);
      btnDel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
          DemandsActivity.db.execSQL("delete from " + Helper.TBL_DEMAND + " where " + BaseColumns._ID + "=" + demandId);
          Intent intent = new Intent();
          setResult(RESULT_OK, intent);
          finish();
        }

      });

      if (sended) {
        btnSave.setEnabled(false);
        btnDel.setEnabled(false);
      }

      if (sended) {
        spnOsnr.setEnabled(false);
        spnHost.setEnabled(false);
        etInfo.setEnabled(false);
        mDate.setEnabled(false);
      }

      // add a click listener to the button
      mDate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
          showDialog(DATE_DIALOG_ID);
        }
      });

      btnPos = (Button) findViewById(R.id.btnPos);
      btnPos.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
          Intent intent = new Intent(DocHeadActivity.this, DocStockActivity.class);
          //Bundle b = new Bundle();
          //b.putLong("demand_id", 0);
          //intent.putExtras(b);
          startActivityForResult(intent, DemandsActivity.POS_REQUEST_CODE);
        }
      });
      countPosAndSum();

      findViewById(R.id.dummyfocus).setFocusableInTouchMode(true);
      findViewById(R.id.dummyfocus).requestFocus();
    } catch (Exception e) {
      DemandsException.dialogError(this, e, true);      
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == DemandsActivity.POS_REQUEST_CODE) {
      countPosAndSum();
    }
  }
  
  @Override
  public void onResume() {
    super.onResume();
    findViewById(R.id.dummyfocus).setFocusableInTouchMode(true);
    findViewById(R.id.dummyfocus).requestFocus();
  }

  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
      Calendar c1 = Calendar.getInstance();
      c1.setTime(date);
      int year = c1.get(Calendar.YEAR);
      int month = c1.get(Calendar.MONTH);
      int day = c1.get(Calendar.DAY_OF_MONTH);

      return new DatePickerDialog(this, mDateSetListener, year, month, day);
    }
    return null;
  }

  // the callback received when the user "sets" the date in the dialog
  private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
      Calendar c = Calendar.getInstance();
      c.set(year, monthOfYear, dayOfMonth);
      date = c.getTime();
      updateDisplayDate();
      isEdited = true;
    }

  };

  private void countPosAndSum(){
    Cursor c = DemandsActivity.db.rawQuery("select count(id_tu) as cnt,sum(amount*price) as summa from "+DocHeadActivity.TBL_TEMP_ITEM, null);
    c.moveToFirst();
    float summa = c.getFloat(c.getColumnIndex("summa"));
    DecimalFormat df;
    df = new DecimalFormat("#0.00");
    btnPos.setText("Позиций "+String.valueOf(c.getInt(c.getColumnIndex("cnt")))+" на "+df.format(summa)+" руб.");
    c.close();
    
  }
  
  
  private void updateDisplayDate() {
    final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    mDate.setText(sdf.format(date));
  }

  private static final String OsnrFields[] = { Helper.TBL_OSNR_NAME, BaseColumns._ID };
  private static final int[] OsnrTo = new int[] { android.R.id.text1 };

  public void setAdapterOsnr(Context c) {
    Cursor data = DemandsActivity.db.rawQuery("select " + BaseColumns._ID + "," + Helper.TBL_OSNR_NAME + " from " + Helper.TBL_OSNR + " where " + Helper.TBL_OSNR_IS_ARC + "=0", null);
    data.moveToFirst();
    startManagingCursor(data);
    if (spnOsnr != null) {
      SimpleCursorAdapter adapter = new SimpleCursorAdapter(c, android.R.layout.simple_spinner_item, data, OsnrFields, OsnrTo);
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spnOsnr.setAdapter(adapter);
    }
  }

  private static final String HostFields[] = { Helper.TBL_HOST_NAME, BaseColumns._ID };
  private static final int[] HostTo = new int[] { android.R.id.text1 };

  public void setAdapterHost(Context c) {
    Cursor data = DemandsActivity.db.rawQuery("select " + BaseColumns._ID + "," + Helper.TBL_HOST_NAME + " from " + Helper.TBL_HOST + " where " + Helper.TBL_HOST_IS_ARC + "=0", null);
    data.moveToFirst();
    startManagingCursor(data);
    if (spnHost != null) {
      SimpleCursorAdapter adapter = new SimpleCursorAdapter(c, android.R.layout.simple_spinner_item, data, HostFields, HostTo);
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spnHost.setAdapter(adapter);
    }
  }

  public void saveDemand() {
    ContentValues cv = new ContentValues();
    cv.put(Helper.TBL_DEMAND_ID_AGENT, agentId);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    cv.put(Helper.TBL_DEMAND_DATE, sdf.format(date));
    cv.put(Helper.TBL_DEMAND_DEMAND_DATE, sdf.format(demandDate));
    cv.put(Helper.TBL_DEMAND_ID_HOST, spnHost.getSelectedItemId());
    cv.put(Helper.TBL_DEMAND_ID_OSNR, spnOsnr.getSelectedItemId());
    cv.put(Helper.TBL_DEMAND_INFO, etInfo.getText().toString());
    cv.put(Helper.TBL_DEMAND_ADDIT, 0);
    if (insertMode) {
      String s = "select max(" + BaseColumns._ID + ") as maxid from " + Helper.TBL_DEMAND;
      int maxId = 0;
      Cursor data = DemandsActivity.db.rawQuery(s, null);
      if (data.moveToFirst()) {
        maxId = data.getInt(0);
      }
      if (!data.isClosed())
        data.close();
      int optionMaxId;
      try {
        optionMaxId = Integer.parseInt(DemandsActivity.getOptionValue("MAX_ID"));
        maxId = Math.max(maxId, optionMaxId);
      } catch (Exception e) {
      }
      demandId = maxId + 1;
      cv.put(BaseColumns._ID, demandId);
      DemandsActivity.db.insert(Helper.TBL_DEMAND, null, cv);
    } else {
      cv.put(BaseColumns._ID, demandId);
      DemandsActivity.db.replace(Helper.TBL_DEMAND, null, cv);
      DemandsActivity.db.execSQL("delete from " + Helper.TBL_DEMAND_LINE + " where " + Helper.TBL_DEMAND_LINE_ID_DEMAND + "=" + demandId);
    }

    DemandsActivity.db.execSQL("insert into " + Helper.TBL_DEMAND_LINE + " (" + Helper.TBL_DEMAND_LINE_ID_DEMAND + "," + Helper.TBL_DEMAND_LINE_ID_TU + "," + Helper.TBL_DEMAND_LINE_AMOUNT + ","
        + Helper.TBL_DEMAND_LINE_PRICE + ") select " + demandId + "," + DocTabActivity.TBL_TEMP_ITEM_ID_TU + "," + DocTabActivity.TBL_TEMP_ITEM_AMOUNT + "," + DocTabActivity.TBL_TEMP_ITEM_PRICE + " from "
        + DocTabActivity.TBL_TEMP_ITEM + "");
  }

  @Override
  public void onBackPressed() {
    super.onBackPressed();
    //((DocTabActivity) this.getParent()).myOnBackPressed();
  }
}